package com.ruoyi.yljf.controller.AppController;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.security.annotation.Anonymous;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.SysDictDataVO;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.yljf.domain.*;
import com.ruoyi.yljf.domain.dto.CourseDTO;
import com.ruoyi.yljf.domain.dto.SearchDTO;
import com.ruoyi.yljf.domain.dto.WelfareAreaQueryDTO;
import com.ruoyi.yljf.domain.enums.yljfEnums;
import com.ruoyi.yljf.domain.vo.*;
import com.ruoyi.yljf.service.*;
import com.ruoyi.yljf.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 课程Controller
 *
 * @author TC
 * @date 2025-02-19
 */
@RestController
@Anonymous
@RequestMapping("/api/homeCourse")
public class ApiCourseController extends BaseController {

    @Autowired
    private ICourseService courseService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ICoursePackageService coursePackageService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IMedicalRecordService medicalRecordService;
    @Autowired
    private IDrugService drugService;
    @Resource
    private ICollectRecordService collectRecordService;
    @Resource
    private CommonUtils commonUtils;
    @Resource
    private IQuestionService questionService;

    @Autowired
    private ICoursewareService coursewareService;

    /**
     * type
     *
     * @param type
     * @return
     */
    @GetMapping("/getDictType")
    public AjaxResult getCourseType(String type) {
        return success(dictDataService.selectDictDataList(type));
    }

    /**
     * 首页精选课程查询
     *
     * @return
     */
    @GetMapping("/querySiftCourse")
    public AjaxResult querySiftCourse() {
        //查询课程所有分类
        List<SysDictDataVO> secondaryType = dictDataService.selectDictDataList("secondary_type");
        //查询每个分类的课程信息
        List<CourseTypeVO> list = courseService.getSiftCourse(secondaryType);
        return success(list);
    }

    /**
     * 首页入门必学课程查询
     *
     * @return
     */
    @GetMapping("/queryPrimaryCourse")
    public AjaxResult queryPrimaryCourse() {
        //查询入门必学课程
        return success(courseService.queryPrimaryCourse());
    }

    @GetMapping("/queryStarCourse")
    public AjaxResult queryStarCourse() {
        //查询名家视频课程
        return success(courseService.queryStarCourse());
    }

    @GetMapping("/coursePaper")
    public AjaxResult coursePaper() {
        return success(questionService.qyeryExamList());
    }


    /**
     * 首页查询课程
     */
    @GetMapping("/list")
    public TableDataInfo list(CourseDTO courseDTO) {
        startPage();
        List<HomeCourseVO> list = courseService.queryCourseList(courseDTO);
        return getDataTable(list);
    }

    /**
     * 课程详情
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id, HttpServletRequest request) {
        CourseDetailVO courseDetailVO = courseService.queryById(id, request);
        if (courseDetailVO != null && commonUtils.userIfLogin(request))
            courseDetailVO.setIfCollect(collectRecordService.ifCollect(yljfEnums.COURSE.getCode(), id, getUserId()));
        return success(courseDetailVO);
    }

    /**
     * 课程目录
     */
    @GetMapping(value = "/coursePackage/{id}")
    public AjaxResult getCoursePackage(@PathVariable("id") Long id) {
        List<PackageVO> list = coursePackageService.getByCourseID(id);
        return success(list);
    }

    /**
     * 课程章节积分记录
     */
    @GetMapping(value = "/getCourseScoreRecord/{id}")
    public AjaxResult getCourseScoreRecord(@PathVariable("id") Long id) {
        List<PackageScoreRecordVO> list = coursePackageService.getCourseScoreRecord(id);
        return success(list);
    }

    /**
     * 关键字搜索课程目录
     */
    @GetMapping(value = "/coursePackageByKeyWord")
    public AjaxResult getCoursePackageByKeyWord(Long id, String keyWord) {
        List<PackageVO> list = coursePackageService.getByCourseID(id);
        List<PackageVO> collect1 = list.stream().filter(packageVO -> {
            List<CoursePackageVO> collect = packageVO.getList()
                    .stream()
                    .filter(coursePackageVO -> coursePackageVO.getTitle().contains(keyWord))
                    .collect(Collectors.toList());
            if (collect == null || collect.size() == 0)
                return false;
            packageVO.setList(collect);
            return true;
        }).collect(Collectors.toList());
        return success(collect1);
    }

    /**
     * 公益专区类型查询
     */
    @GetMapping("/queryWelfareAreaType")
    public AjaxResult queryWelfareAreaType() {
        List list = courseService.queryWelfareAreaType();
        return success(list);
    }

    /**
     * 公益专区类型查询V2
     */
    @GetMapping("/queryWelfareAreaTypeV2")
    public AjaxResult queryWelfareAreaTypeV2() {
        List list = courseService.queryWelfareAreaTypeV2();
        return success(list);
    }

    /**
     * 公益专区接口
     */
    @GetMapping("/queryWelfareArea")
    public TableDataInfo queryWelfareArea(WelfareAreaQueryDTO dto) {
        startPage();
        List<Course> courses = courseService.queryCourseList(dto);
        List<HomeCourseVO> hvos = BeanUtil.copyToList(courses, HomeCourseVO.class);
        return getDataTableInfo(hvos, courses);
    }

    /**
     * 首页-精选课程--查看更多
     */
    @GetMapping("/selectList")
    public TableDataInfo selectList(CourseDTO courseDTO) {
        startPage();
        courseDTO.setIsFeatured("Y");
        List<HomeCourseVO> list = courseService.queryCourseList(courseDTO);
        return getDataTable(list);
    }

    /**
     * 首页-入门必学--查看更多
     */
    @GetMapping("/primaryList")
    public TableDataInfo primaryList(CourseDTO courseDTO) {
        courseDTO.setGrade("primary");
        startPage();
        List<Course> list = courseService.queryCourseList1(courseDTO);
        List<HomeCourseVO> listVO = courseService.QueryHomeCourseList(list);
        return getDataTableInfo(listVO, list);
    }

    /**
     * 合方-名家视频--查看更多
     */
    @GetMapping("/starList")
    public TableDataInfo starList() {
        startPage();
        List<HomeCourseVO> list = courseService.queryStarList();
        return getDataTable(list);
    }


    /**
     * 首页-搜索接口
     */
    @GetMapping("/homeSearch")
    public TableDataInfo homeSearch(SearchDTO dto) {
        startPage();
        if (dto.getType() == 1) {               //查询文章
            Article article = new Article();
            article.setCreateType("admin");
            article.setTitle(dto.getKeyWord());
            List<Article> list = articleService.selectArticleList(article);
            List collect = new ArrayList();
            if (ObjectUtils.isNotEmpty(list)) {
                collect = list.stream().map(item -> {
                    ArticleVO articleVO = new ArticleVO();
                    BeanUtil.copyProperties(item, articleVO);
                    return articleVO;
                }).collect(Collectors.toList());
            }

            // 查询其他的数量
            return getDataTableInfo(collect, list);

        } else if (dto.getType() == 2) {
            Course course = new Course();
            course.setName(dto.getKeyWord());
            List<Course> list = courseService.selectCourseList(course);
            List collect = new ArrayList();
            if (ObjectUtils.isNotEmpty(list)) {
                collect = list.stream().map(item -> {
                    Course5VO vo = new Course5VO();
                    vo.setName(item.getName());
                    vo.setId(item.getId());
                    vo.setImg(item.getImg());
                    vo.setCreateTime(item.getCreateTime());
                    return vo;
                }).collect(Collectors.toList());
            }
            return getDataTableInfo(collect, list);
        } else if (dto.getType() == 3) {
            MedicalRecord medicalRecord = new MedicalRecord();
            medicalRecord.setRecordName(dto.getKeyWord());
            List<MedicalRecord> list = medicalRecordService.selectMedicalRecordList(medicalRecord);
            List collect = new ArrayList();
            if (ObjectUtils.isNotEmpty(list)) {
                collect = list.stream().map(item -> {
                    Course5VO vo = new Course5VO();
                    vo.setName(item.getRecordName());
                    vo.setId(item.getRecordId());
                    //TODO 没有图片,需要核对展示列表
//                vo.setImg(item.getImg());
                    vo.setCreateTime(item.getCreateTime());
                    return vo;
                }).collect(Collectors.toList());
            }
            return getDataTableInfo(collect, list);
        } else if (dto.getType() == 4) {
            Drug drug = new Drug();
            drug.setName(dto.getKeyWord());
            List<Drug> list = drugService.selectDrugList(drug);
            List collect = new ArrayList();

            if (ObjectUtils.isNotEmpty(list)) {
                collect = list.stream().map(item -> {
                    Course5VO vo = new Course5VO();
                    vo.setName(item.getName());
                    vo.setId(item.getId());
                    //TODO 需要确定图片是单张还是多张，多张的话，需要裁切
                    vo.setImg(item.getImages());
                    vo.setCreateTime(item.getCreateTime());
                    return vo;
                }).collect(Collectors.toList());
            }


            return getDataTableInfo(collect, list);
        }
        return null;
    }

    /**
     * 首页-搜索-头部数据
     */
    @GetMapping("/homeSearchTop")
    public AjaxResult homeSearchTop(SearchDTO dto) {

        Article article = new Article();
        article.setCreateType("admin");
        long count1 = articleService.count(new LambdaQueryWrapper<>(Article.class)
                .eq(Article::getCreateType, "admin")
                .like(StringUtils.isNotEmpty(dto.getKeyWord()), Article::getTitle, dto.getKeyWord()));
        SearchTopVO vo1 = new SearchTopVO("文章", count1);

        // 查询课程数量
        long count2 = courseService.count(new LambdaQueryWrapper<>(Course.class)
                .like(StringUtils.isNotEmpty(dto.getKeyWord()), Course::getName, dto.getKeyWord()));
        SearchTopVO vo2 = new SearchTopVO("课程", count2);

        // 查询医案数量
        long count3 = medicalRecordService.count(new LambdaQueryWrapper<>(MedicalRecord.class)
                .like(StringUtils.isNotEmpty(dto.getKeyWord()), MedicalRecord::getRecordName, dto.getKeyWord()));
        SearchTopVO vo3 = new SearchTopVO("医案", count3);

        // 查询药材数量
        long count4 = drugService.count(new LambdaQueryWrapper<>(Drug.class)
                .like(StringUtils.isNotEmpty(dto.getKeyWord()), Drug::getName, dto.getKeyWord()));
        SearchTopVO vo4 = new SearchTopVO("药材", count4);

        LinkedList<SearchTopVO> searchTopVOS = new LinkedList<>();
        searchTopVOS.add(vo1);
        searchTopVOS.add(vo2);
        searchTopVOS.add(vo3);
        searchTopVOS.add(vo4);

        return success(searchTopVOS);
    }


    //
    /*查询课件列表*/
    @GetMapping("/getCourseWare")
    public TableDataInfo getCourseWare(Courseware courseware) {
        List<Courseware> coursewares = coursewareService.selectCoursewareList(courseware);
        if (coursewares == null || coursewares.size() == 0)
            return getDataTableInfo(new ArrayList<>(), new ArrayList<>());
        List<CoursewareVO> vos = BeanUtil.copyToList(coursewares, CoursewareVO.class);
        return getDataTableInfo(vos, coursewares);
    }

    //
    /*查询课件详情*/
    @GetMapping("/getCourseWareDetail")
    public AjaxResult getCourseWareDetail(Courseware courseware) {
        Courseware result = coursewareService.selectCoursewareDetail(courseware);
        if (Objects.isNull(result)) return success();
        return success(result);
    }

}
